package com.qfedu.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.fmmall.vo.ResultStatus;
import com.qfedu.fmmall.vo.ResultVo;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.UnsupportedJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component  //把组件加入到spring中
public class CheckTokenInterceptor implements HandlerInterceptor {
    /**
     * @Author  Liux8
     * Date 2021-9-23
     * 设置token拦截器
     * */

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       /**
        * toekn 有效返回true
        * */
       //浏览器发送请求前会有一次试探行请求，也是浏览器三次握手中的第一次握手，如果握手成功，会响应回来，才会发起正确的请求方式
       //试探性请求的请求方式是OPTIONS，我们需要把他跳过
        String method = request.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            System.out.println(method);
            return  true;
        }


        String token = request.getHeader("token");//通过请求头来传递token
        if(token==null){
            ResultVo resultVo = new ResultVo(ResultStatus.LOGIN_FAIL_NOT, "请先登录哟", null);
            //提示请先登录
            doResponse(response,resultVo);
        }else{
            String s = stringRedisTemplate.boundValueOps(token).get();
            if(s == null){
                ResultVo resultVo = new ResultVo(ResultStatus.LOGIN_FAIL_NOT, "请先登录哟", null);
                //提示请先登录
                doResponse(response,resultVo);
            }else{
                //续命
                stringRedisTemplate.boundValueOps(token).expire(30, TimeUnit.MINUTES);
                return true;
            }


            /**
            try{
                //验证token
                JwtParser parser = Jwts.parser();
                //解析token的SigningKey必须和生成token时设置密码一致
                parser.setSigningKey("QIANFeng6666");
                //如果token正确（密码正确，有效期内）则正常执行，否则抛出异常
                parser.parseClaimsJws(token);
                return true;
            }catch (ExpiredJwtException e){
                ResultVo resultVo = new ResultVo(ResultStatus.LOGIN_FAIL_OVERDUE, "登录过期，请重新登录", null);
                doResponse(response,resultVo);
            }catch (UnsupportedJwtException e){
                ResultVo resultVo = new ResultVo(ResultStatus.NO, "token不合法，请自重", null);
                doResponse(response,resultVo);
            }catch (Exception e){
                ResultVo resultVo = new ResultVo(ResultStatus.LOGIN_FAIL_NOT, "请先登录哦", null);
                doResponse(response,resultVo);
            }
             **/
        }
        return false;
    }

    /**
     * 封装token验证失败时返回的数据
     * */
    private void doResponse(HttpServletResponse response, ResultVo resultVo) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        String s = new ObjectMapper().writeValueAsString((resultVo));//传需要显示提示的内容
        writer.print(s);
        writer.flush();
        writer.close();
    }
}
